package com.niit.chat.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Jackson 配置类
 * 配置 LocalDateTime 序列化和反序列化
 */
@Configuration
public class JacksonConfig {

    private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    /**
     * 配置并返回一个自定义的ObjectMapper实例
     * 用于处理LocalDateTime类型的序列化和反序列化
     * 
     * @return 配置好的ObjectMapper实例
     */
    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();

        /*
         * 创建JavaTimeModule实例
         * 用于注册LocalDateTime的序列化和反序列化器
         */
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        
        /*
         * 配置LocalDateTime的序列化和反序列化格式
         * 使用预定义的日期时间格式模式创建序列化器和反序列化器
         */
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_TIME_PATTERN);
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter));
        
        /*
         * 将配置好的JavaTimeModule注册到ObjectMapper中
         * 完成对LocalDateTime类型的序列化和反序列化支持的配置
         */
        objectMapper.registerModule(javaTimeModule);
        
        return objectMapper;
    }
} 